package m.jclecai.com.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.Request;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.base.recyclerview.BaseRecyclerViewAdapter;
import m.jclecai.com.base.recyclerview.BaseViewHolder;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.Response.ResQrCodeBeanList;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;

/**
 * Created by Dinosa on 2018/1/4.
 */

public class RedPackSendFriendActivity extends BaseActivity {

    @BindView(R.id.et_phone_number)
    EditText mEtPhoneNumber;

    @BindView(R.id.et_money)
    EditText mEtMoney;

    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;

    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    private QrCodeAdapter mQrCodeAdapter;

    @Override
    protected int getContentView() {
        return R.layout.activity_send_red_pack;
    }

    @Override
    protected void initView() {
        super.initView();
        //这里要执行的一个操作激就是显示
        setTitle("赠送给朋友");
        leftOptionText("");
        rightOptionText("我的好友");

        tvRightOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RedPackSendFriendActivity.this, InvitedFriendActivity.class));

            }
        });

        StringBuffer qr = new StringBuffer();
        qr.append("http://116.206.178.47:8081/inviteQrcode.php?");
        qr.append("user="+PreferenceUtil.getUserName(this));
        qr.append("&password="+PreferenceUtil.getPassword(this));
        Glide.with(this)
                .load(qr.toString())
                .into(ivQrCode);
    }


    @Override
    protected void initData() {
        super.initData();

        mRvList.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        mQrCodeAdapter = new QrCodeAdapter(null);
        mRvList.setAdapter(mQrCodeAdapter);

        getData();

    }

    private void getData() {
        //这里是获取信息；
        HttpManager.getAsyn(Constant_Url.GET_QR_CODE_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {

                DisPlay("网络异常！！！");

            }

            @Override
            public void onResponse(String response) {

                if (!TextUtils.isEmpty(response)) {

                    ResQrCodeBeanList resQrCodeBeanList = FastOk.get(response, ResQrCodeBeanList.class);
                    if (resQrCodeBeanList != null) {
                        mQrCodeAdapter.refresh(resQrCodeBeanList.getRecords());
                    } else {
                        DisPlay("网络异常！！！");
                    }
                } else {
                    DisPlay("网络异常！！！");
                }

            }
        });

    }

    @Override
    protected void initListener() {
    }

    /**
     * 这里是点击确定的按钮；
     */
    @OnClick(R.id.tv_sure)
    public void onClickSure() {

        String phoneNumber = mEtPhoneNumber.getText().toString();
        String money = mEtMoney.getText().toString();
        //对输入内容进行一个确认；
        if (!isPhoneNumber(phoneNumber)) {
            DisPlay("请输入正确的手机号!!!");
            return;
        }

        if (TextUtils.isEmpty(money)) {
            DisPlay("请输入金额");
            return;
        }

        HashMap<String, String> paramsMap = new HashMap<>();

        paramsMap.put("user", PreferenceUtil.getUserName(this));
        paramsMap.put("password", PreferenceUtil.getPassword(this));
        paramsMap.put("phone", phoneNumber);
        paramsMap.put("money", money);

        showDialog();
        //这里我们要做提交服务器；
        HttpManager.postAsyn(Constant_Url.SEND_RED_PACK, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常!!!");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                try {
                    if (!TextUtils.isEmpty(response)) {
                        //这里对数据进行一个解析；
                        ProofBean proofBean = FastOk.get(response, ProofBean.class);
                        if ("0".equals(proofBean.getStatus())) {
                            DisPlay("赠送成功！！！");
                        } else {
                            DisPlay(proofBean.getMessage());
                        }
                    } else {
                        DisPlay("网络异常！！！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DisPlay("网络异常！！！");
                }
            }
        }, paramsMap);

    }

    public boolean isPhoneNumber(String phoneNumber) {
        //这里是检查手机号的；
        if (!TextUtils.isEmpty(phoneNumber)) {
            return true;
        }
        return false;
    }

    public class QrCodeAdapter extends BaseRecyclerViewAdapter<ResQrCodeBeanList.QrCodeBean> {

        public QrCodeAdapter(List<ResQrCodeBeanList.QrCodeBean> DList) {
            super(DList);
        }

        @Override
        public int getItemView() {
            return R.layout.item_qr_code_list;
        }

        @Override
        protected void bindViewHolder(final BaseViewHolder holder, final ResQrCodeBeanList.QrCodeBean bean, int position) throws ParseException {

            holder.getTextView(R.id.tv_desc).setText(bean.getName());
            Glide.with(RedPackSendFriendActivity.this).load(bean.getImage()).into(holder.getImageView(R.id.iv_qr_code));


            //holder.getImageView(R.id.iv_qr_code).setDrawingCacheEnabled(true);

            holder.getImageView(R.id.iv_qr_code).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这里执行保存二维码的操作；
                    ImageView imageView = holder.getImageView(R.id.iv_qr_code);
                   /* Bitmap drawingCache = imageView.getDrawingCache();
                    imageView.setDrawingCacheEnabled(false);
                    //这里我们是需要将图片保存在相册里面的；
                    saveBmp2Gallery(drawingCache,bean.getName());*/
                    saveImage(imageView
                    );
                }
            });
        }
    }

    private void saveImage(ImageView imageView) {
        imageView.setDrawingCacheEnabled(true);//开启catch，开启之后才能获取ImageView中的bitmap
        Bitmap bitmap = imageView.getDrawingCache();//获取imageview中的图像
        MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "这是title", "这是description");
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        imageView.setDrawingCacheEnabled(false);//关闭catch

    }


    /**
     * @param bmp     获取的bitmap数据
     * @param picName 自定义的图片名
     */
    public void saveBmp2Gallery(Bitmap bmp, String picName) {

        String fileName = null;
        //系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;


        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;

        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName + ".jpg");

            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            if (null != outStream) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            }

        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MediaStore.Images.Media.insertImage(RedPackSendFriendActivity.this.getContentResolver(),
                bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);
        DisPlay("保存到相册！！！");
    }
}
